package com.yc.pre.entity;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiModel;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collections;
import java.util.List;

/**
 * @author DoyuTu
 */
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
@ApiModel(description = "分页信息",value = "分页信息")
public class PageResult<T> {

    private int page = Pageable.DEFAULT_PAGE;

    private int num = Pageable.DEFAULT_NUM;

    private long total;

    private int pages = 1;

    private boolean hasNext;

    private List<T> list;

    public static <T> PageResult<T> of(PageInfo<T> info) {
        return of(info, info.getList());
    }

    public static <T> PageResult<T> of(PageInfo<?> info, List<T> result) {
        if (info == null || result == null) {
            return new PageResult<>();
        }
        return new PageResult<>(info.getPageNum(), info.getPageSize(), info.getTotal(), info.getPages(), info.isHasNextPage(), result);
    }

    /*public static <T> PageResult<T> of(AggregatedPage<T> info) {
        return of(info.getContent(), info);
    }

    public static <T> PageResult<T> of(List<T> data, AggregatedPage info) {
        long total = info.getTotalElements();
//        total = NumberUtils.min(info.getTotalElements(), 10000);
        int size = info.getSize();
        return new PageResult<>(info.getNumber() + 1, size, total, size == 0 ? 1 : (int) (total + size - 1) / size, info.hasNext(), data);
    }*/

    public static <T> PageResult<T> of(Long totalCount, Pageable pageable, List<T> data) {
        int totalPage = (int) Math.ceil((float) totalCount / pageable.getNum());
        return new PageResult<>(pageable.getPage(), pageable.getNum(), totalCount, totalPage, pageable.getPage() < totalPage, data);
    }
    public static <T> PageResult<T> ofPage(Long totalCount, Pageable pageable, List<T> data){
        int totalPage = (int) Math.ceil((float) totalCount / pageable.getNum());
        List<T> newList = data.subList(pageable.getNum() * (pageable.getPage() - 1), (int) Math.min((pageable.getNum() * pageable.getPage()), totalCount));
        return new PageResult<>(pageable.getPage(), pageable.getNum(), totalCount, totalPage, pageable.getPage() < totalPage, newList);
    }

    public static <T> PageResult<T> empty(Pageable pageable) {
        return new PageResult<>(pageable.getPage(), pageable.getNum(), 0, 0, false, Collections.emptyList());
    }

}
